package com.weyoung.app.consumer;

import com.weyoung.app.event.AccessEvent;
import com.weyoung.app.service.AccessStatsService;
import com.weyoung.app.service.DeviceStatsService;
import com.weyoung.app.service.NetworkStatsService;
import com.weyoung.common.config.RabbitMQConfig;
import com.weyoung.entity.AccessStats;
import com.weyoung.entity.DeviceStats;
import com.weyoung.entity.NetworkStats;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

/**
 * 统计消息消费者
 * 处理异步统计消息，更新各类统计数据
 */
@Slf4j
@Component
public class StatsMessageConsumer {

    @Autowired
    private NetworkStatsService networkStatsService;
    
    @Autowired
    private DeviceStatsService deviceStatsService;
    
    @Autowired
    private AccessStatsService accessStatsService;

    /**
     * 处理统计消息
     * 接收并处理来自RabbitMQ的访问统计消息
     *
     * @param event 访问事件对象
     */
    @RabbitListener(queues = RabbitMQConfig.STATS_QUEUE)
    @Transactional(rollbackFor = Exception.class)
    public void handleStatsMessage(AccessEvent event) {
        try {
            LocalDate today = LocalDate.now();

            // 处理网络统计
            NetworkStats networkStats = NetworkStats.builder()
                    .url(event.getUrl())
                    .userId(event.getUserId())
                    .date(java.sql.Date.valueOf(today))
                    .network(event.getNetwork())
                    .build();
            networkStatsService.saveOrUpdateStats(networkStats);

            // 处理设备统计
            DeviceStats deviceStats = DeviceStats.builder()
                    .url(event.getUrl())
                    .userId(event.getUserId())
                    .date(java.sql.Date.valueOf(today))
                    .device(event.getDevice())
                    .build();
            deviceStatsService.saveOrUpdateStats(deviceStats);

            // 处理访问统计
            AccessStats accessStats = AccessStats.builder()
                    .userId(event.getUserId())
                    .url(event.getUrl())
                    .date(java.sql.Date.valueOf(today))
                    .pv(1)
                    .uv(1)
                    .uip(1)
                    .build();
            accessStatsService.saveOrUpdateStats(accessStats);
            
        } catch (Exception e) {
            log.error("处理统计消息失败", e);
            throw e;
        }
    }
} 